import { useState, useEffect, useRef } from 'react'


/*
 useState 让函数组件有了state
 
*/
const DemoState = () => {
  const [number, setnumber] = useState(0)

  const NumberSub = () => {
    setnumber(number - 1)
  }

  const NumberAdd = () => {
    setnumber(number => number + 1)
  }

  return (
    <div>
      <p>{number}</p>
      <button onClick={NumberSub}> number --</button>
      <button onClick={NumberAdd}> number ++</button>
    </div>
  )
}

/*
 useEffect 让函数组件有了生命周期
*/
const DemoEffect = ({ name }) => {
  console.log('name', name);
  const [userMessage, setUseMessage] = useState({})
  const [age, setAge] = useState(18)
  const div = useRef()
  /**
   * useEffect 第一个参数接受一个函数
   * 第二个参数
   *    如果没有，会死循环调用useEffect
   *    如果是一个空数组，那么会执行一次相当于componentDidMount 
   *    如果是[name], 那么只有当 name 改变是，会重复执行一次
  */
  useEffect(() => {
    /* 模拟数据交互 */
    function getUserInfo(name) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve({
            name,
            age
          })
        }, 500)
      })
    }


    /* 请求数据 */
    getUserInfo(name)
      .then(res => {
        console.log("调了一次接口", res);
        setUseMessage(res)
      })

    /* 操作dom */
    console.log(div.current);
    /* 下面一行注释不可删，作用:eslint将不对下一行代码检测  */
    // eslint-disable-next-line
  }, [age])

  const staffs = [
    {
      name: "修言",
      career: "前端"
    },
    {
      name: "翠翠",
      career: "编辑"
    }
  ]

  const changeAge = () => {
    setAge(age + 1)
  }

  return (
    <div ref={div}>
      <p>{userMessage.name}</p>
      <p>{userMessage.age}</p>
      <button onClick={changeAge}>age ++</button>


      <table>
        {staffs.forEach((staffs) => {
          <tr>
            <td>{% staffs.name %}</td>
            <td>{% staffs.career %}</td>
          </tr>
        })}
      </table>
    </div>
  )

}

/*
useEffect可以用作事件监听，还有一些基于dom的操作。
  别忘了在useEffect第一个参数回调函数，返一个函数用于清除事件监听等操作。
*/
const DemoEffectCleal = ({ id }) => {
  const [name, setName] = useState('')
  const handleChage = () => {
    console.log("函数触发");
  }

  const getUserName = () => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          userName: "小毅" + id
        })
      }, 1000)
    })
  }

  useEffect(() => {
    getUserName(id)
      .then(res => {
        setName(name => name = res.userName)
      })
    // eslint-disable-next-line
  }, [id])
  return (
    <div>
      {name ? <p>姓名是:{name}</p> : <p>等待接口返回数据...</p>}
    </div>
  )
}


export {
  DemoState,
  DemoEffect,
  DemoEffectCleal,
}
